﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db4objects.Db4o;
using System.Configuration; 

namespace CoolCode.DataSource.DB4O
{
    public class DataBase : IDisposable, CoolCode.DataSource.IDataBase 
    {
        private IObjectContainer _db;
        private string _connectionString;

        public IObjectContainer DB
        {
            get { 
                if(_db ==null)
                    _db =Db4oFactory.OpenFile (_connectionString );
                return _db; 
            }
        }

        public DataBase()
            : this(System.Web.VirtualPathUtility.GetFileName( ConfigurationManager.AppSettings["ConnectionString"]))
        {
        }

        public DataBase(string connectionString)
        {
            _connectionString = connectionString;
            _db  = Db4oFactory.OpenFile(connectionString);
        }

        public virtual  void Store<T>(T TEntity)
        {
            DB.Store(TEntity);
        }
        
        public virtual  void  Delete<T>(T TEntity)
        {
            DB.Delete(TEntity);
        }

        public virtual void StoreAll<T>(IEnumerable<T> TList)
        {
            foreach (var TEntity in TList)
                DB.Store(TEntity);
        }

        public virtual void DeleteAll<T>(IEnumerable <T> TList)
        {
            foreach (var TEntity in TList)
                DB.Delete(TEntity);
        }

        public virtual IList<T> Query<T>()
        {
            return DB.Query<T>();
        }

        public virtual  IList<T> Query<T>(Predicate<T> predicate)
        {
           return   DB.Query<T>(predicate);
        }

        public virtual  IList<T> Query<T>(Predicate<T> predicate, Comparison<T> comparision)
        {
            return DB.Query<T>(predicate,comparision );
        }

        public virtual bool Contains<T>(Predicate<T> predicate)
        {
            var q = DB.Query(predicate );
            return q.Count > 0;
        }

        public virtual bool Contains(Object template)
        {
            var q = DB.QueryByExample(template);
            return q.Count > 0;
        }

        #region IDisposable Members

        public void Dispose()
        {
            if(DB!=null)
            DB.Close();
        }

        #endregion
    }
}
